package com.ihealthway.all.groupbuy.services;

import com.ihealthway.all.utils.Utils;
import com.ihealthway.all.groupbuy.vo.ImageLibrary;
import com.ihealthway.all.commons.Constants;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Files;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.upload.TempFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Image library service
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean(fields = {"dao"})
public class ImageLibraryService extends BaseService<ImageLibrary> {

    private static final Log logger = Logs.get();

    public List<ImageLibrary> getImagesOnFront(Integer goodsId) {
        return dao().query(ImageLibrary.class, Cnd.where("goods_id", "=", goodsId.intValue()));
    }

    public List<ImageLibrary> getShopAdImgs() {
        Criteria cri = Cnd.cri();
        cri.where().and("remarks", "=", "ad");
        cri.where().and("data_status", "=", "0");
        cri.getOrderBy().asc("order_no");

        Pager pager = new Pager();
        pager.setPageSize(4);

        try {
            List<ImageLibrary> imgs =  query(cri, pager);
            return imgs;
        } catch (Exception e) {
            logger.error("Get shop index ad image info failure!!!", e);
            return null;
        }
    }

    public boolean updateGoodsImg(String imgIds, Integer goodsId) {
        Sql removeGoods = Sqls.create("UPDATE gb_images_library SET goods_id = NULL WHERE goods_id = "+goodsId.intValue());
        Sql addGoods = Sqls.create("UPDATE gb_images_library SET goods_id = '"+goodsId.intValue()+"' WHERE img_id IN ("+imgIds+")");
        try {
            dao().execute(removeGoods, addGoods);
        } catch (Exception e) {
            logger.error("Update goods info failure!!!", e);
            return false;
        }

        return true;
    }

    public boolean updateShopAdImg(NutMap nm) {

        boolean flag = false;

        List<ImageLibrary> shopAdImgs = new ArrayList<>();

        shopAdImgs.add(getFromNM(0, nm));
        shopAdImgs.add(getFromNM(1, nm));
        shopAdImgs.add(getFromNM(2, nm));
        shopAdImgs.add(getFromNM(3, nm));

        try {
            int effectRows = _updateIgnoreNull(shopAdImgs);
            flag = (effectRows > 0);
        } catch (Exception e) {
            logger.error("Update show ad image info failed.", e);
        }

        return flag;
    }

    private ImageLibrary getFromNM(int index, NutMap nm) {
        ImageLibrary adImg = new ImageLibrary();
        adImg.setUpdateTime(new Date());
        adImg.setImgId(nm.getInt("adId["+index+"]"));
        String[] adImgTmp = nm.getString("adImgTmp["+index+"]").split(",");
        if (adImgTmp.length > 1 && adImgTmp.length == 4) {
            adImg.setImgName(adImgTmp[0]);
            adImg.setImgUrl(adImgTmp[1]);
            adImg.setImgType(adImgTmp[2]);
            adImg.setImgSize(Long.valueOf(adImgTmp[3]));
        }
        adImg.setImgLink(nm.getString("adLink["+index+"]"));
        return adImg;
    }

    public boolean updateImg(ImageLibrary imgLib) {

        boolean update = false;

        imgLib.setUpdateTime(new Date());
        try {
            int effectRows = _updateIgnoreNull(imgLib);
            update = (effectRows > 0);
        } catch (Exception e) {
            logger.error(imgLib);
            logger.error("Update image library failed.", e);
        }

        return update;
    }

    public void uploadGoodsImg(NutMap nm, String savePath) {

        logger.infof("Goods img save path: %s", savePath);
        TempFile goodsImgTmpFile = ((TempFile) nm.get("file"));
        File goodsImgFile = goodsImgTmpFile.getFile();
        String newImgName = Utils.renameUploadFile(goodsImgFile.getName());
        String imgPath = savePath + "/" + newImgName;
        String imgURL = Constants.GOODS_IMG_CTX_PATH+newImgName;
        logger.infof("GoodsImg display context url: %s", imgURL);

        ImageLibrary goodsImg = new ImageLibrary();
        goodsImg.setCreateTime(new Date());
        goodsImg.setImgName(goodsImgTmpFile.getSubmittedFileName());
        goodsImg.setImgUrl(imgURL);
        goodsImg.setImgType(nm.getString("type"));
        goodsImg.setImgSize(nm.getLong("size"));
        goodsImg.setImgLink("#");
        goodsImg.setOrderNo(0);
        goodsImg.setDataStatus("0");
        goodsImg.setRemarks(goodsImgTmpFile.getSubmittedFileName());

        try {
            Files.copyFile(goodsImgFile, new File(imgPath));
        } catch (IOException e) {
            logger.error("Upload goods image failed!!!", e);
        }

        try {
            _insert(goodsImg);
        } catch (Exception e) {
            logger.error("Save goods image failed!!!", e);
        }
    }

    public ImageLibrary uploadShopAdImg(NutMap nm, String savePath) {

        logger.infof("Shop index ad save path: %s", savePath);
        TempFile adImgTempFile = ((TempFile) nm.get("adImg"));
        File adImgFile = adImgTempFile.getFile();
        String newImgName = Utils.renameUploadFile(adImgFile.getName());
        String adImgPath = savePath + "/" + newImgName;
        String imgURL = Constants.SHOP_AD_CTX_PATH+newImgName;
        logger.infof("Shop index ad display context url: %s", imgURL);

        ImageLibrary adImg = new ImageLibrary();
        adImg.setImgId(nm.getInt("imgId"));
        adImg.setUpdateTime(new Date());
        adImg.setImgName(adImgTempFile.getSubmittedFileName());
        adImg.setImgSize(adImgTempFile.getFile().length());
        adImg.setImgType("image/png");
        adImg.setImgUrl(imgURL);
        adImg.setOrderNo(nm.getInt("orderNo"));
        adImg.setRemarks(adImgTempFile.getSubmittedFileName());

        try {
            Files.copyFile(adImgFile, new File(adImgPath));
        } catch (IOException e) {
            logger.error("Upload shop index ad image failed.", e);
        }
        return adImg;
    }

    public Map<String, Object> getUnUsedData(Integer companyId) {
        Criteria cri = Cnd.cri();
        cri.where().andIsNull("remarks");
        cri.where().andIsNull("goods_id");
        if (companyId != null && companyId.intValue()!=0) {
            cri.where().orEquals("goods_id", companyId);
        }
        Map<String, Object> data = easyuiDGPager(-1, -1, cri);
        return data;
    }

    public Map<String, Object> getData(int rows, int page) {
        Criteria cri = Cnd.cri();
        cri.where().andIsNull("remarks");
        Map<String, Object> data = easyuiDGPager(page, rows, cri);
        return data;
    }
}
